from django.contrib import messages
from django.http import *
from django.shortcuts import render
from django.core.paginator import Paginator
from .models import Notice
from .models import User
from department.models import Department


# Create your views here.


def all_notice(request: HttpRequest):

    return render(request, 'notice/all_notice.html')


def page_notice(request: HttpRequest):
    query = request.GET.get("keyword")
    if not query:
        print('a')
        departments = Department.objects.get(title=request.session["user.department"].title)
        departments = Department.objects.filter(dep_path__startswith=request.session['user.department'].dep_path)
        notices = Notice.objects.filter()
    else:
        print('b')
        notices = Notice.objects.filter(title__contains=query)
    # 表格要展现的数据
    # 处理成LayUi官方文档的格式
    lis = []
    for notice in notices:
        data = dict()
        data['id'] = notice.id
        data['title'] = notice.title
        data['content'] = notice.content
        data['release_time'] = notice.release_time
        data['updated_time'] = notice.updated_time
        data['read_time'] = notice.read_time
        data['preferred_grade'] = notice.preferred_grade
        data['user_type'] = notice.user_type
        # 格式化时间的格式
        lis.append(data)
        # 前台传来的页数
        # 创建分页器
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    notice_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式/
    notices = {"code": 0, "msg": "", "count": notices.count(), "data": notice_info}
    return JsonResponse(notices)


def add_notice(request:HttpRequest):
    if request.method == 'GET':
        return render(request, 'notice/add_notice.html', locals())
    elif request.method == 'POST':
        # 1.接收用户在表单中输入的数据
        title = request.POST['title']
        content = request.POST['content']
        preferred_grade = request.POST['preferred_grade']
        user_type = request.POST['user_type']

        if not title or not content:
            # messages.error('标题或内容为空')
            return JsonResponse({'state': 2})

        # 数据入库
        Notice.objects.create(title=title,
                              content=content,
                              preferred_grade=preferred_grade,
                              user_type=user_type,
                              user=request.session['user'],
                              department=request.session['user.department'])
        # 重定向
        return JsonResponse({'state':1})


def update_notice(request:HttpRequest):
    # notice = Notice.objects.get(id=uid)
    if request.method == 'GET':
        uid = request.GET.get('id')
        try:
            notice = Notice.objects.get(id=uid)
        except:
            return HttpResponseNotFound
        return render(request, 'notice/update_notice.html', locals())
    elif request.method == 'POST':
        # 1.接收用户在表单中输入的数据
        uid = request.POST['id']
        title = request.POST['title']
        content = request.POST['content']
        preferred_grade = request.POST['preferred_grade']
        user_type = request.POST['user_type']
        try:
            notice = Notice.objects.get(id=uid)
        except:
            return JsonResponse({'state': 3})
        notice.title = title
        notice.content = content
        notice.preferred_grade = preferred_grade
        notice.user_type = user_type
        # 保存
        notice.save()
        return JsonResponse({'state': 1})


def del_notice(request: HttpRequest):
    #  从查询字符串当中获取公告编号
    uid = request.POST['id']
    notice = Notice.objects.get(id=uid)
    notice.delete()
    return JsonResponse({'state': 1})


def detail_notice(request: HttpRequest):
    if request.method == "GET":
        uid = request.GET.get('id')
        try:
            notice = Notice.objects.get(id=uid)
        except:
            return HttpResponseNotFound
        return render(request, 'notice/detail_notice.html', locals())